package com.zrl.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrl.service.MessageService;
import com.zrl.utils.ConstantPropertiesUtil;
import com.zrl.utils.HttpClientUtils;
import com.zrl.utils.SHA1;
import me.chanjar.weixin.common.error.WxErrorException;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zrl
 * @date: 2022/8/23 11:40
 * @description:
 */
@RestController
@RequestMapping("/api/wechat/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    //token
    private static final String token = "love";

    private String Location;


    private static Map<String,String> data = new HashMap<>();



    //接收微信服务器发送来的消息
    @PostMapping
    public String receiveMessage(HttpServletRequest request) throws Exception {
        Map<String, String> param = this.parseXml(request);
        System.out.println(param);
        //处理接收到的消息
        String content = messageService.receiveMessage(param);
        //获取经纬度
        String msgType = param.get("MsgType");
        String location = "";
        if ("event".equals(msgType)){
            String event = param.get("Event");
            if ("LOCATION".equals(event)){
                String longitude = param.get("Longitude");
                String latitude = param.get("Latitude");
                location = formatLocation(longitude, latitude);
                System.out.println(location);
                if (data.isEmpty()){
                    data.put("location",location);
                    messageService.getWeather(data);
                    messageService.getCity(data);
                    messageService.getdate(data);
                    messageService.getcontent(data);
                }
            }
        }
        return content;
    }


    //发送消息
    @GetMapping("/pushMessage")
    public String pushPayMessage() throws WxErrorException {

        messageService.pushMessage(data);
        return "ok";
    }

    @PostMapping ("/clearMapData")
    public void clearMap(){
        messageService.cleaerMapData(data);
    }

    //服务器有效性验证
    @GetMapping
    public String verifyToken(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if (this.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return "error";
    }

    //对经纬度取精度为小数点后两位
    public String formatLocation(String longitude,String latitude){
//        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        Double longitude1 = Double.valueOf(longitude);
        Double latitude1 = Double.valueOf(latitude);
        String string1 = String.format("%.2f", longitude1).toString();
        String string2 = String.format("%.2f", latitude1).toString();

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(string1);
        stringBuffer.append(",");
        stringBuffer.append(string2);
        return stringBuffer.toString();
    }

    //具体验证方法
    private boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] str = new String[]{token, timestamp, nonce};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp = SHA1.encode(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }

    //转换xml为Map
    private Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        inputStream = null;
        return map;
    }


//定时任务
   @Scheduled(cron =" 0 30 08 ? * *")
    public void dopushTask(){

        String url = "http://localhost:8080/api/wechat/message/pushMessage";
        HttpClientUtils httpClient = new HttpClientUtils(url);
       try {
           httpClient.get();
       } catch (IOException e) {
           e.printStackTrace();
           throw new RuntimeException("执行定时任务失败");
       }

   }

    @Scheduled(cron =" 0 0 08 ? * *")
    public void dodeleteTask(){

        String url = "http://localhost:8080/api/wechat/message/clearMapData";
        HttpClientUtils httpClient = new HttpClientUtils(url);
        try {
            httpClient.post();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("执行定时任务失败");
        }

    }


}

